package P2PConnection;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * Authors: Henrique Alberto Rusa and Danilo Barbosa Porto
 * Date: 03/12/13
 *
 * FTPClient class implements the client that will connect to the FTPServer on our application.
 * This class will have the job of sending a file through the socket connection established with the server and than end
 * the connection.
 * The protocol will have a SEND affirmative from the client and a DISCONNECT to close the connection also from the client.
 */
public class FTPClient {

    private final int portNumber = 8756;

    //Socket to connect with the server over FTP
    Socket clientSocket;

    // Parameter that reads data over the FTP connection
    DataInputStream dataInput;

    // Parameter thar writes data over the FTP connection
    DataOutputStream dataOutput;

    /*
     * Constructor of class FTPClient.
     * This method will allocate memory to the attributes of the class and link the socket where the client will
     * connect with the FTPServer.
     */
    public FTPClient(InetAddress client){
        try {
            clientSocket = new Socket(client,portNumber);
            dataInput   = new DataInputStream(clientSocket.getInputStream());
            dataOutput  = new DataOutputStream(clientSocket.getOutputStream());
        } catch (IOException e) {
            //TODO
        }
    }

    /*
     * sendFile method implements the send of a file using the socket connection.
     * It will verify if the file were found on the client, and if it is valid, it will inform the server though the SEND
     * command to receive the data, then it will disconnect using the DISCONNECT command.
     */
    public void sendFile(String filename) throws IOException {

        /*
         * Creates a new file to handle the send of data.
         * If file that was requested to send does not exists, it informs the server and closes the connection.
         */
        File arq = new File(filename);
        if(!arq.exists()){
            dataOutput.writeUTF("File Not Found");
            return;
        }

        // Informs the server of the filename of the sending file.
        dataOutput.writeUTF(filename);

        // Creates the file reader and an integer to get end of file
        FileInputStream fileInput =new FileInputStream(arq);
        int charBuffer;

        /*
         * Here the code flag the sending of a file to the server and send the data.
         * When end of file is reached, close file reader and disconnect from server.
         */
        dataOutput.writeUTF("SEND");
        do
        {
            charBuffer = fileInput.read();
            dataOutput.writeUTF(String.valueOf(charBuffer));
        }
        while(charBuffer != -1);
        fileInput.close();
    }
}





















